package com.itbour.common.util;

import java.io.File;

import com.itbour.common.log.DebugLogger;
import com.itbour.def.SystemConf;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.squareup.okhttp.RequestBody;

public class QnFileUtil {
	public static final String TYPE_IMAGE = "image";
	public static final String TYPE_AUDIO = "audio";
	public static final String TYPE_VIDEO = "video";
	
	private static final String ACCESS_KEY = SystemConf.getQnAccessKey();
    private static final String SECRET_KEY = SystemConf.getQnSecretKey();
    private static final String BUCKET_NAME = SystemConf.getQnBucket();
    
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    public void uploadTest() {

    	String upToken = auth.uploadToken(BUCKET_NAME, null);
  
    	File file = new File("/Users/itbour/Desktop/share/1.jpg");
    	Response res = null;
    	try {
    		UploadManager uploadMgr= new UploadManager();
            res = uploadMgr.put(file, "1.jpg", upToken);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            DebugLogger.log(r.toString());
            try {
                // 响应的文本信息
            	DebugLogger.log(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }
    
    /**
     * 获取七牛上传token
     * @param type image/audio/video
     * @param userId
     * @return uploadToken [(type)/("U"+userId/"T"+random)/(YYYYMMDDhhmmss)/(hash)]
     */
    public static String getToken(String type, Long userId) {
    	String upType = QnFileUtil.TYPE_IMAGE;
    	if (StringUtils.isNotBlank(type)) {
    		upType = type;
    	}
    	
    	String id = "T0";
    	if (userId != null && userId >= 0) {
    		id = "U" + String.valueOf(userId);
    	} else {
    		long tmp = (long)Math.random()*1000000;
    		id = "T" + String.valueOf(tmp);
    	}
    	
    	StringMap policy = new StringMap();
    	policy.put("insertOnly", 1)// 仅能以新增模式上传文件
    	//.putNotEmpty("saveKey", type+"/$(year)$(mon)$(day)$(hour)$(min)$(sec)/$(fname)")// 自定义资源名
    	.putNotEmpty("saveKey", type+"/"+id+"/$(year)$(mon)$(day)$(hour)$(min)$(sec)/$(etag)")// 自定义资源名
    	.putNotEmpty("mimeLimit", "image/*");// 只允许上传图片类型
    	
    	String token = auth.uploadToken(BUCKET_NAME, null, 3600, policy);
    	return token;
    }
}
